import React from 'react'
import { Form, Button, Select, Input, message, Spin, Empty, Modal, Space } from 'antd'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import moment from 'moment'
import style from './RoomBookDetail.module.less'
import { ApproveBlock, Header, Line, Cell, Split, Footer } from '@components/ApprovePre/Approve'
import BookRoomSelector from '@components/BookRoomSelector/Index'
import ArbitratorSelector from '@components/ArbitratorManage/ArbitratorSelector'
const { Item } = Form
const { Option } = Select
class RoomBookDetail extends Component {
  state = {
    type: '系统案件',
    caseList: [],
    loading: false,
    selectorVisible: false,
    bookInfo: '',
    courtType: '独任庭',
    arbitratorSelectorVisible: false,
    arbitratoridKey: '',
    arbitratorKey: '',
    arbitratorSelectdId: '',
    arbitratorDisabledIds: [],
    dictionaries: {} // 枚举字典
  }

  formRef = React.createRef()

  // 改变案件类型
  changeType (t) {
    if (t === '旧系统案件') {
      this.setState({
        courtType: '独任庭'
      })
      this.formRef.current.setFieldsValue({ tribunal_type_redundant: '独任庭' })
    }
    this.setState({
      type: t
    }, () => {
      const d = this.props.meta.data
      this.formRef.current.setFieldsValue({
        caseid: d ? d.caseid : undefined,
        caseno_desc: d ? d.caseno_desc : undefined,
        processer_redundant: undefined,
        caseno_desc_redundant: undefined,
        arbitrators_redundant: undefined
      })
    })
  }

  // 获取案件列表数据
  getCaseData (s) {
    this.timer && clearTimeout(this.timer)
    this.timer = setTimeout(() => {
      this.setState({ loading: true })
      this.$get('/api/xapc/case', {
        condition: JSON.stringify([{ k: 'caseno_desc', o: 'like', v: `%${s}%` }])
      }).then(res => {
        this.setState({ loading: false })
        if (res.status === 1) {
          this.setState({
            caseList: res.data.list
          })
        } else {
          message.warning(res.message)
        }
      }).catch(() => this.setState({ loading: false }))
    }, 500)
  }

  // 修改案号
  changeCaseno (e) {
    let id = ''
    const list = this.state.caseList
    for (let i = 0; i < list.length; i++) {
      if (list[i].caseno_desc === e) {
        id = list[i].id
      }
    }
    this.formRef.current.setFieldsValue({
      caseid: id,
      caseno_desc: e
    })
  }

  // 隐藏预约庭室弹框
  hideBookRoomSelector () {
    this.setState({
      selectorVisible: false
    })
  }

  // 改变约庭信息
  modifyBookInfo (bookInfo) {
    this.setState({
      bookInfo,
      selectorVisible: false
    }, () => {
      const b = bookInfo
      this.formRef.current.setFieldsValue({
        bookInfo: `${b.room_name}（${b.date} ${b.start_time} ～ ${b.end_time}）`
      })
    })
  }

  // 确定提交输入
  submitInput (data) {
    if (data.id) {
      this.updateBookRequest(data)
    } else {
      this.addBookRequest(data)
    }
  }

  // 取消
  cancel () {
    this.props.delWindow(this.props.id)
    this.props.addWindow({ id: 'RoomBookList', title: '庭室使用情况', componentName: 'RoomBookList', forceRefresh: true, meta: { } })
  }

  // 确认添加预约庭室
  addBookRequest (o) {
    const hide = message.loading('预约庭室中', 120)
    const b = this.state.bookInfo
    this.$post('/api/xapc/hearingroombook', {
      hearingroomid: b.room_id,
      begin_datetime: Math.floor(moment(`${b.date} ${b.start_time}`).valueOf() / 1000),
      end_datetime: Math.floor(moment(`${b.date} ${b.end_time}`).valueOf() / 1000),
      caseid: o.caseid,
      remark: o.remark,
      use: o.use,
      status: 1,
      processer_redundant: o.processer_redundant,
      caseno_desc_redundant: o.caseno_desc_redundant,
      tribunal_type_redundant: o.tribunal_type_redundant,
      arbitratorid_redundant: o.arbitratorid_redundant,
      arbitratorid1_redundant: o.arbitratorid1_redundant,
      arbitratorid2_redundant: o.arbitratorid2_redundant,
      arbitrator_redundant: o.arbitrator_redundant,
      arbitrator1_redundant: o.arbitrator1_redundant,
      arbitrator2_redundant: o.arbitrator2_redundant
    }).then(res => {
      hide()
      if (res.status === 1) {
        Modal.success({
          title: '新增成功',
          okText: '确定',
          onOk: () => {
            this.props.delWindow(this.props.id)
            this.props.addWindow({ id: 'RoomBookList', title: '庭室使用情况', componentName: 'RoomBookList', forceRefresh: true, meta: { } })
          }
        })
      } else {
        message.warning(res.message)
      }
    }).catch(() => hide())
  }

  // 更新约庭
  updateBookRequest (o) {
    const hide = message.loading('更改预约中', 120)
    const b = this.state.bookInfo
    this.$put(`/api/xapc/hearingroombook/${o.id}`, {
      hearingroomid: b.room_id,
      begin_datetime: Math.floor(moment(`${b.date} ${b.start_time}`).valueOf() / 1000),
      end_datetime: Math.floor(moment(`${b.date} ${b.end_time}`).valueOf() / 1000),
      caseid: o.caseid,
      remark: o.remark,
      use: o.use,
      status: 1,
      processer_redundant: o.processer_redundant,
      caseno_desc_redundant: o.caseno_desc_redundant,
      tribunal_type_redundant: o.tribunal_type_redundant,
      arbitratorid_redundant: o.arbitratorid_redundant,
      arbitratorid1_redundant: o.arbitratorid1_redundant,
      arbitratorid2_redundant: o.arbitratorid2_redundant,
      arbitrator_redundant: o.arbitrator_redundant,
      arbitrator1_redundant: o.arbitrator1_redundant,
      arbitrator2_redundant: o.arbitrator2_redundant
    }).then(res => {
      hide()
      if (res.status === 1) {
        Modal.success({
          title: ' 修改成功',
          okText: '确定',
          onOk: () => {
            this.props.delWindow(this.props.id)
            this.props.addWindow({ id: 'RoomBookList', title: '庭室使用情况', componentName: 'RoomBookList', forceRefresh: true, meta: { } })
          }
        })
      } else {
        message.warning(res.message)
      }
    }).catch(() => hide())
  }

  // 初始化数据
  initData () {
    if (!this.props.meta.data) {
      return false
    }
    const { data } = this.props.meta
    const date = moment(data.begin_datetime * 1000).format('YYYY-MM-DD')
    const start = moment(data.begin_datetime * 1000).format('HH:mm')
    const end = moment(data.end_datetime * 1000).format('HH:mm')
    const b = {
      room_name: data.name,
      room_id: data.hearingroomid,
      date,
      start_time: start,
      end_time: end
    }
    this.setState({
      type: data.caseid ? '系统案件' : '旧系统案件',
      bookInfo: b,
      courtType: data.tribunal_type_redundant,
      caseid: data.caseid
    })
    this.formRef.current.setFieldsValue({
      id: data.id,
      caseid: data.caseid ? data.caseid : undefined,
      caseno_desc: data.caseno_desc,
      processer_redundant: data.processer_redundant,
      caseno_desc_redundant: data.caseno_desc_redundant,
      tribunal_type_redundant: data.tribunal_type_redundant,
      arbitratorid_redundant: data.arbitratorid_redundant,
      arbitratorid1_redundant: data.arbitratorid1_redundant,
      arbitratorid2_redundant: data.arbitratorid2_redundant,
      arbitrator_redundant: data.arbitrator_redundant,
      arbitrator1_redundant: data.arbitrator1_redundant,
      arbitrator2_redundant: data.arbitrator2_redundant,
      remark: data.remark,
      use: data.use,
      bookInfo: `${b.room_name}（${b.date} ${b.start_time} ～ ${b.end_time}）`
    })
  }

  // 改变庭室类型
  changeCourtType (v) {
    this.setState({
      courtType: v
    })
    this.formRef.current.setFieldsValue({
      tribunal_type_redundant: v
    })
  }

  // 关闭仲裁员选择器
  hideArbitratorSelector () {
    this.setState({
      arbitratorSelectorVisible: false,
      arbitratoridKey: '',
      arbitratorKey: '',
      arbitratorSelectdId: '',
      arbitratorDisabledIds: []
    })
  }

  // 显示仲裁员选择器
  showArbitratorSelector (idKey, nameKey) {
    const keys = ['arbitratorid_redundant', 'arbitratorid1_redundant', 'arbitratorid2_redundant']
    const index = keys.indexOf(idKey)
    keys.splice(index, 1)
    this.setState({
      arbitratorSelectorVisible: true,
      arbitratoridKey: idKey,
      arbitratorKey: nameKey,
      arbitratorDisabledIds: keys.map(key => this.formRef.current.getFieldValue(key)),
      arbitratorSelectdId: this.formRef.current.getFieldValue(idKey)
    })
  }

  onChangeArbitrator (d) {
    const { arbitratoridKey, arbitratorKey } = this.state
    this.setState({
      arbitratorSelectorVisible: false,
      arbitratoridKey: '',
      arbitratorKey: '',
      arbitratorDisabledIds: [],
      arbitratorSelectdId: ''
    })
    this.formRef.current.setFieldsValue({
      [arbitratoridKey]: d.id,
      [arbitratorKey]: d.name
    })
  }

  // 获取枚举的字典值
  getDictionary () {
    this.$get('/api/xapc/dictionary', {
      types: '庭室用途'
    }).then(res => {
      if (res.status === 1) {
        // 设置枚举字典
        const dictionaries = this.formatDictionaries(res.data)
        this.setState({
          dictionaries
        })
      } else {
        message.error(res.message)
      }
    })
  }

  // 格式化枚举字典
  formatDictionaries (dictionaries = []) {
    const result = {}
    dictionaries.forEach(d => {
      result[d.type] = d.list
    })
    return result
  }

  componentDidMount () {
    this.getDictionary()
    this.initData()
  }

  // 当加载中，渲染加载动画
  renderNotFound () {
    if (this.state.loading) {
      return <div className={style['loading-box']}><Spin /></div>
    }
    return <div className={style['loading-box']}><Empty image={Empty.PRESENTED_IMAGE_SIMPLE} /></div>
  }

  // 渲染案号录入
  renderCasenoInput () {
    if (this.state.type !== '系统案件') {
      return (
        <Item label='案号' name='caseno_desc_redundant' rules={[{ required: true, message: '案号不能为空' }]}>
          <Input placeholder='请输入案号' />
        </Item>
      )
    }
    return (
      <Item label='案号' name='caseno_desc' rules={[{ required: true, message: '案号不能为空' }]}>
        <Select placeholder='请选择案号' onSearch={e => this.getCaseData(e)} onChange={e => this.changeCaseno(e)} showSearch showArrow={false} allowClear notFoundContent={this.renderNotFound()}>
          {this.state.caseList.map(li => <Option key={li.id} value={li.caseno_desc}>{li.caseno_desc}</Option>)}
        </Select>
      </Item>
    )
  }

  // 渲染其他案件的字段
  renderOtherParam () {
    if (this.state.type === '系统案件') {
      return null
    }
    const priLable = this.state.courtType === '独任庭' ? '独任仲裁员' : '首席仲裁员'
    return (
      <Line>
        <Cell>
          <Item label='办案秘书' name='processer_redundant' rules={[{ required: true, message: '办案秘书不能为空' }]}>
            <Input placeholder='请输入办案秘书' />
          </Item>
        </Cell>
        <Split />
        <Cell>
          <Item label='仲裁庭类型' name='tribunal_type_redundant' rules={[{ required: true, message: '仲裁庭类型' }]}>
            <Select placeholder='请选择仲裁庭类型' onChange={v => this.changeCourtType(v)}>
              <Option key='独任庭'>独任庭</Option>
              <Option key='三人庭'>三人庭</Option>
            </Select>
          </Item>
        </Cell>
        <Split />
        <Cell>
          <Item name='arbitratorid_redundant' noStyle><span /></Item>
          <Item label={priLable} name='arbitrator_redundant' rules={[{ required: true, message: `${priLable}不能为空` }]}>
            <Input placeholder={`请选择${priLable}`} readOnly onClick={() => this.showArbitratorSelector('arbitratorid_redundant', 'arbitrator_redundant')} />
          </Item>
        </Cell>
      </Line>
    )
  }

  // 当庭室类型为三人庭时，渲染其他仲裁员
  renderOtherArbitrators () {
    if (this.state.type === '系统案件' || this.state.courtType === '独任庭') {
      return null
    }
    return (
      <>
        <Cell>
          <Item name='arbitratorid1_redundant' noStyle><span /></Item>
          <Item label='仲裁员一' name='arbitrator1_redundant' rules={[{ required: true, message: '仲裁员一不能为空' }]}>
            <Input placeholder='请选择仲裁员一' readOnly onClick={() => this.showArbitratorSelector('arbitratorid1_redundant', 'arbitrator1_redundant')} />
          </Item>
        </Cell>
        <Split />
        <Cell>
          <Item name='arbitratorid2_redundant' noStyle><span /></Item>
          <Item label='仲裁员二' name='arbitrator2_redundant' rules={[{ required: true, message: '仲裁员二不能为空' }]}>
            <Input placeholder='请选择仲裁员二' readOnly onClick={() => this.showArbitratorSelector('arbitratorid2_redundant', 'arbitrator2_redundant')} />
          </Item>
        </Cell>
        <Split />
      </>
    )
  }

  render () {
    const data = {}
    const meta = this.props.meta || {}
    const isModify = (meta.data || {}).id
    const useList = this.state.dictionaries['庭室用途'] || []
    return (
      <div className={style.container}>
        <ArbitratorSelector visible={this.state.arbitratorSelectorVisible} hide={() => this.hideArbitratorSelector()} onChange={d => this.onChangeArbitrator(d)} disableIds={this.state.arbitratorDisabledIds} selectedId={this.state.arbitratorSelectdId} />
        <div className={style['title-line']}>
          <span>{isModify ? '修改' : '新增'}预约庭室</span>
        </div>
        <div className={style['book-block']}>
          <Form name='room-book-detail' ref={this.formRef} labelCol={{ flex: '96px' }} initialValues={data} onFinish={v => this.submitInput(v)}>
            <Item noStyle name='id'><span /></Item>
            <Item noStyle name='caseid'><span /></Item>
            <ApproveBlock>
              <Header title='预约庭室' />
              <Line>
                {/* <Cell>
                  <Item label='案件类型'>
                    {this.state.type}
                    <Select placeholder='请选择仲裁庭类型' value={this.state.type} onChange={(e) => this.changeType(e)}>
                      <Option key='系统案件'>系统案件</Option>
                      <Option key='其他案件'>其他案件</Option>
                    </Select>
                  </Item>
                </Cell>
                <Split /> */}
                <Cell>
                  {this.renderCasenoInput()}
                </Cell>
                <Split />
                <Cell>
                  <Item label='约庭信息' name='bookInfo' rules={[{ required: true, message: '庭室信息不能为空' }]}>
                    <Input placeholder='请输入约庭信息' readOnly onClick={() => this.setState({ selectorVisible: true })} />
                  </Item>
                </Cell>
                <Cell>
                  <Item label='庭室用途' name='use' rules={[{ required: true, message: '庭室用途' }]}>
                    <Select placeholder='请选择庭室用途'>
                      {useList.map(li => (
                        <Option key={li.title} value={li.value}>{li.title}</Option>
                      ))}
                    </Select>
                  </Item>
                </Cell>
              </Line>
              {/* {this.renderOtherParam()}
              <Line>
                {this.renderOtherArbitrators()}
                <Cell>
                  <Item label='庭室用途' name='use' rules={[{ required: true, message: '庭室用途' }]}>
                    <Select placeholder='请选择庭室用途'>
                      {useList.map(li => (
                        <Option key={li.title} value={li.value}>{li.title}</Option>
                      ))}
                    </Select>
                  </Item>
                </Cell>
              </Line> */}
              <Footer>
                <Line>
                  <Cell style={{ width: '65%' }}>
                    <Item label='备注' name='remark' style={{ marginBottom: 0 }}>
                      <Input placeholder='请输入备注' style={{ width: '100%' }} />
                    </Item>
                  </Cell>
                  <Split />
                  <Cell style={{ textAlign: 'right' }}>
                    <Space>
                      <Button onClick={() => this.cancel()}>取消</Button>
                      <Button type='primary' onClick={() => this.formRef.current.submit()}>确认</Button>
                    </Space>
                  </Cell>
                </Line>
              </Footer>
            </ApproveBlock>
          </Form>
        </div>
        <BookRoomSelector visible={this.state.selectorVisible} value={this.state.bookInfo} hide={() => this.hideBookRoomSelector()} onChange={v => this.modifyBookInfo(v)} />
      </div>
    )
  }
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
  }
})

export default connect(mapState, mapDispatch)(RoomBookDetail)
